<script>
import { ref, reactive, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { api } from '../api'
import { ElMessage } from 'element-plus'

export default {
  name: 'AddCourse',
  setup() {
    const userStore = useUserStore()
    const courseForm = reactive({
      name: '',
      description: '',
      teacherName: '',
      startDate: '',
      endDate: '',
      categoryId: ''
    })
    
    const categories = ref([])
    const courseFormRef = ref(null)
    
    const rules = {
      name: [
        { required: true, message: '请输入课程名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入课程简介', trigger: 'blur' },
        { min: 10, max: 200, message: '长度在 10 到 200 个字符', trigger: 'blur' }
      ],
      teacherName: [
        { required: true, message: '请输入老师姓名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      startDate: [
        { required: true, message: '请选择开始日期', trigger: 'change' }
      ],
      endDate: [
        { required: true, message: '请选择结束日期', trigger: 'change' },
        // 新增：确保结束日期晚于开始日期
        {
          validator: (rule, value, callback) => {
            if (!value) {
              return callback(new Error('请选择结束日期'))
            }
            if (courseForm.startDate && value < courseForm.startDate) {
              return callback(new Error('结束日期不能早于开始日期'))
            }
            callback()
          },
          trigger: 'change'
        }
      ],
      categoryId: [
        { required: true, message: '请选择课程类别', trigger: 'change' }
      ]
    }
    
    // 获取课程类别列表
    const fetchCategories = async () => {
      try {
        console.log('准备获取课程类别...');
        
        // 直接调用API获取真实数据，不再使用默认数据
        const response = await api.items.getAll(5);
        console.log('API响应数据:', response);
        
        // 处理API响应
        if (response?.errno === 0 && response.data && Array.isArray(response.data)) {
          // 将数据转换为下拉框需要的格式
          categories.value = response.data.map(item => ({
            id: item.id || item.categoryId || item._id,
            name: item.title || item.name || '未命名类别'
          })).filter(item => item.name); // 过滤掉空名称的类别
          
          console.log('成功获取课程类别:', categories.value);
          
          // 如果没有类别，提示用户添加
          if (categories.value.length === 0) {
            ElMessage.info('当前暂无课程类别，请先添加类别');
          }
        } else {
          // 处理不符合预期的响应格式
          console.warn('API返回的数据格式不符合预期:', response);
          ElMessage.warning('获取课程类别数据格式异常');
        }
      } catch (error) {
        console.error('获取课程类别失败:', error);
        ElMessage.error('获取课程类别失败，请稍后重试');
      }
    };
    
    // 提交表单
    const submitForm = async () => {
      const form = courseFormRef.value
      if (!form) return
      
      try {
        await form.validate()
        
        // 准备提交数据，包含用户ID
        const submitData = {
          name: courseForm.name,
          description: courseForm.description,
          teacherName: courseForm.teacherName,
          startDate: courseForm.startDate,
          endDate: courseForm.endDate,
          categoryId: courseForm.categoryId,
          // 优化用户标识获取逻辑，优先使用id，再尝试其他字段
          userId: userStore.userInfo?.id || userStore.userInfo?.stuNum || userStore.userInfo?.username || 'default_user'
        }
        
        console.log('提交的课程数据:', submitData)
        // 调用API添加课程，6是课程在表数组中的索引
        const response = await api.items.add(submitData, 6)
        
        // 正确处理后端响应格式
        if (response?.errno === 0) {
          ElMessage.success('课程添加成功')
          resetForm()
          // 添加成功后重新获取类别列表，确保数据最新
          setTimeout(() => {
            fetchCategories();
          }, 500); // 延迟执行，确保后端数据已更新
        } else {
          ElMessage.error(response?.message || '课程添加失败')
        }
      } catch (error) {
        console.error('添加课程失败:', error)
        if (error.name !== 'ValidateError') {
          ElMessage.error('网络错误，请稍后重试')
        }
      }
    }
    
    // 重置表单
    const resetForm = () => {
      const form = courseFormRef.value
      if (form) {
        form.resetFields()
        // 重置后重新获取类别列表，确保最新数据
        fetchCategories()
      }
    }
    
    // 组件挂载时获取课程类别
    onMounted(() => {
      fetchCategories()
    })
    
    return {
      courseForm,
      rules,
      categories,
      courseFormRef,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.add-course-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-top: 2rem;
}

.add-course-container h2 {
  font-size: 1.8rem;
  color: #333;
  margin-bottom: 1.5rem;
  text-align: center;
  padding-bottom: 1rem;
  border-bottom: 2px solid #42b983;
}

.course-form {
  margin-top: 1rem;
}

.el-form-item {
  margin-bottom: 1.5rem;
}

/* 修复文字输入显示问题 */
.el-form-item__content {
  line-height: 1.8;
}

/* 确保输入框内文字可见 - 全局样式增强 */
:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  line-height: 1.8 !important;
  color: #000000 !important; /* 使用纯黑色提高对比度 */
  background-color: #ffffff !important;
  border-color: #dcdfe6 !important;
  padding: 12px !important;
  font-size: 14px !important;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif !important;
  opacity: 1 !important;
  caret-color: transparent !important; /* 去掉光标选中时的蓝色竖线 */
}

/* 确保输入框焦点状态的可见性 */
:deep(.el-input__inner:focus),
:deep(.el-textarea__inner:focus) {
  color: #000000 !important; /* 使用纯黑色提高对比度 */
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2) !important;
  background-color: #ffffff !important;
  caret-color: transparent !important; /* 去掉光标选中时的蓝色竖线 */
}

/* 增强输入框在输入时文字可见性 - 针对各种状态的覆盖样式 */
:deep(.el-input__wrapper),
:deep(.el-textarea__wrapper) {
  background-color: #ffffff !important;
}

:deep(.el-input.is-focus .el-input__inner),
:deep(.el-textarea.is-focus .el-textarea__inner) {
  color: #000000 !important; /* 使用纯黑色提高对比度 */
  background-color: #ffffff !important;
  caret-color: transparent !important; /* 去掉光标选中时的蓝色竖线 */
}

:deep(.el-input__inner::placeholder),
:deep(.el-textarea__inner::placeholder) {
  color: #909399 !important;
  opacity: 1 !important;
}

/* 确保placeholder文字可见 */
.el-input__inner::placeholder,
.el-textarea__inner::placeholder {
  color: #909399;
  opacity: 1;
}

/* 确保下拉框内文字可见 */
.el-select .el-input__inner {
  color: #303133;
  font-size: 14px;
}

/* 确保选项文字可见 */
.el-select-dropdown__item {
  color: #303133;
  font-size: 14px;
  line-height: 1.8;
  padding: 10px 20px;
}

.el-button {
  min-width: 80px;
}

.el-button + .el-button {
  margin-left: 10px;
}

@media (max-width: 768px) {
  .add-course-container {
    padding: 1.5rem;
    margin: 1rem;
  }
  
  .add-course-container h2 {
    font-size: 1.5rem;
  }
  
  .el-form-item__label {
    width: 100px;
  }
}
</style>